package com.example.lib_net.interceptor

import android.net.wifi.p2p.WifiP2pManager.DnsSdTxtRecordListener
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.nio.charset.StandardCharsets

class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val newBuilder = request.newBuilder()
        //请求体->字符串
        val json = bodyToString(request)
        val sign = createSign(json,"240111134737B4389719")
        newBuilder.addHeader("x-api-sign",sign)
        return chain.proceed(newBuilder.build())
    }
    fun bodyToString(request: Request):String{
        val buffer = Buffer()
        request.body?.writeTo(buffer)
        return buffer.readUtf8()
    }
    fun createSign(json:String,salt:String):String{
        val buffer = Buffer()
        buffer.write(json.toByteArray(StandardCharsets.UTF_8))
        buffer.write(salt.toByteArray(StandardCharsets.UTF_8))
        //md5加密
        return buffer.md5().hex()
    }
}